package com.security02.config;

import com.security02.handler.FailureAuthenticationHandler;
import com.security02.handler.NoLoginAuthentication;
import com.security02.handler.SuccessAuthenticationHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private SuccessAuthenticationHandler successAuthenticationHandler;
    @Resource
    private NoLoginAuthentication noLoginAuthentication;
    @Resource
    private FailureAuthenticationHandler failureAuthenticationHandler;
    @Bean
    PasswordEncoder getPassword(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String user="admin";
        String pass=getPassword().encode("123456");
        List<GrantedAuthority> list=new ArrayList<>();
        GrantedAuthority g=new SimpleGrantedAuthority("manager1");
        list.add(g);
        auth.inMemoryAuthentication().withUser(user).password(pass).authorities(list);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .permitAll()
                .successHandler(successAuthenticationHandler)  //登录成功处理逻辑
                .failureHandler(failureAuthenticationHandler) //登录失败处理逻辑
                //异常处理(权限拒绝、登录失效等)
                .and()
                .exceptionHandling().authenticationEntryPoint(noLoginAuthentication)//匿名用户访问无权限资源时的异常处理
                .and()
                .authorizeRequests()
                .antMatchers("/login.html", "/demo/login").permitAll()
                .antMatchers("/demo/a").hasAnyRole("manager1")
                .antMatchers("/demo/b").hasAnyRole("manager2")
                .and().csrf().disable();  //关闭csrf

    }
}
